服务器有时候不能root登录,有时候就得切换到root 。这里用到了paramiko模块的一个功能 invoke_shell() 理论上这个功能就是模拟切换用户执行命令的过程,代码如下
#!/usr/bin/python3
#coding=utf-8
import paramiko,time
private_key = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')
def verification_ssh(host,username,private_key,port,root_pwd,cmd):
s=paramiko.SSHClient()
s.load_system_host_keys()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect(hostname=host,port=int(port),username=username,pkey=private_key)
if username != 'root':
ssh = s.invoke_shell()
time.sleep(0.1)
ssh.send('su - \n')
buff = ''
while not buff.endswith('Password: '):
resp = ssh.recv(9999)
buff +=resp.decode('gbk')
ssh.send(root_pwd)
ssh.send('\n')
buff = ''
while not buff.endswith('# '):
resp = ssh.recv(9999)
buff +=resp.decode('gbk')
ssh.send(cmd)
ssh.send('\n')
buff = ''
while not buff.endswith('# '):
resp = ssh.recv(9999)
buff +=resp.decode('gbk')
s.close()
result = buff
else:
stdin, stdout, stderr = s.exec_command(cmd)
result = stdout.read()
s.close()
return result
res = verification_ssh('172.25.16.38','study',private_key,54321,'xxx','whoami')
功能上可以实现了。这个后边会把执行结果返回一个字符串回来。就可以后边的操作了。
|